package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api(tags = "公共模块")
@Slf4j
@RestController
@RequestMapping("admin/common")
public class CommonController {
    @Autowired
    private AliOssUtil ossUtil;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        //设置随机命名
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        log.info("上传文件的原始命名是:{}", substring);
        String url = null;

        try {
            //使用UUID可以防止同名替换
            String uuid = UUID.randomUUID().toString() + substring;
            url = ossUtil.upload(file.getBytes(), uuid);
        } catch (Exception e) {
            log.error("文件上传失败:{}", e.getMessage());
            return Result.error("文件上传失败");
        }

        return Result.success(url);
    }
}
